using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Data;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

namespace PPCHelpReader
{
	/// <summary>
	/// Summary description for FileSelectDlg.
	/// </summary>
	public class FileSelectDlg : System.Windows.Forms.Form
	{
		private System.Windows.Forms.ListView listView1;
		private System.Windows.Forms.TreeView treeView1;
		private System.Windows.Forms.ColumnHeader columnHeader1;
		private System.Windows.Forms.ColumnHeader columnHeader2;
		private System.Windows.Forms.ToolBar toolBar1;
		private System.Windows.Forms.ToolBarButton tbBtnCancel;
		private System.Windows.Forms.ToolBarButton tbBtnTreeView;
		private System.Windows.Forms.ToolBarButton tbBtnFileView;
		private System.Windows.Forms.ToolBarButton tbBtnSplitView;
		private System.Windows.Forms.ImageList imageList1=null;
		private System.Windows.Forms.ToolBarButton tbBtnOk;

		private string		m_Mask;
		private Rectangle	m_rectTree;		
		private Rectangle	m_rectFiles;
		private System.Windows.Forms.MainMenu mainMenu1;
        /// <summary>
        /// 
        /// </summary>
		public string		FileName;
		private bool		bLandScape=false;
		private bool		m_bBrowseForDirectory=false;
		private bool		m_bExcludeWindowDir=true;

        /// <summary>
        /// Initializes a new instance of the <see cref="FileSelectDlg"/> class.
        /// </summary>
        /// <param name="Mask">The mask.</param>
		public FileSelectDlg(string Mask)
		{
			m_Mask=Mask;
			DialogResult=DialogResult.Cancel;
			Init();			
		}

        /// <summary>
        /// Initializes a new instance of the <see cref="FileSelectDlg"/> class.
        /// </summary>
		public FileSelectDlg()
		{
			m_Mask="*.*";
			Init();			
		}

        /// <summary>
        /// Initializes a new instance of the <see cref="FileSelectDlg"/> class.
        /// </summary>
        /// <param name="bBrowseForDirectory">if set to <c>true</c> [b browse for directory].</param>
		public FileSelectDlg(bool bBrowseForDirectory)
		{
			m_bBrowseForDirectory=bBrowseForDirectory;
			m_Mask="*.*";
			Init();			
		}
		
		private void InitImageList()
		{			
			try
			{												
				imageList1=new ImageList();
				imageList1.ImageSize=new Size(16,16);		

				Assembly execAssembly= Assembly.GetExecutingAssembly();				
				imageList1.Images.Add(GetIcon(execAssembly,@"SelectFileDlg.ok"));// 0
				imageList1.Images.Add(GetIcon(execAssembly,@"SelectFileDlg.Cancel"));// 1
				imageList1.Images.Add(GetIcon(execAssembly,@"SelectFileDlg.TreeView")); // 2
				imageList1.Images.Add(GetIcon(execAssembly,@"SelectFileDlg.FileView")); // 3
				imageList1.Images.Add(GetIcon(execAssembly,@"SelectFileDlg.SplitView")); // 4
				imageList1.Images.Add(GetIcon(execAssembly,@"SelectFileDlg.OpenFolder_16")); // 5
				imageList1.Images.Add(GetIcon(execAssembly,@"SelectFileDlg.Folder_16")); // 6
			}
			catch(Exception)
			{			
			}
                        
			// Changes for Win Mobile 2003 SE  - Thanks to Venkat Polisetti (vpoliset@yahoo.com)
			//	
			// On Dell Axim X30 - WinMobile 2003 SE - File Open Dialog casued ChmReader to crash.
			// This is dew to the way the imagelist is setup.
			//
			treeView1.ImageList=imageList1;

			toolBar1.ImageList=imageList1;                        
			toolBar1.Buttons[0].ImageIndex=0;				
			toolBar1.Buttons[1].ImageIndex=1;

			if (!bLandScape)
			{
				toolBar1.Buttons[2].ImageIndex=2;			
				toolBar1.Buttons[3].ImageIndex=3;				
				toolBar1.Buttons[4].ImageIndex=4;
			}
			else
			{
				toolBar1.Buttons.RemoveAt(4);
				toolBar1.Buttons.RemoveAt(3);
				toolBar1.Buttons.RemoveAt(2);
			}
		}

        /// <summary>
        /// Inits this instance.
        /// </summary>
		public void Init()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();			

			if (Width>Height+52)
				bLandScape=true;

			InitImageList();

			if (bLandScape)
			{
				treeView1.Left=0;
				treeView1.Top=0;
				treeView1.Width=Width/2;
				treeView1.Height=Height;

				listView1.Left=Width/2;
				listView1.Top=0;
				listView1.Width=Width/2;
				listView1.Height=Height;				
			}
			else
			{
				treeView1.Left=0;
				treeView1.Top=0;
				treeView1.Width=Width;
				treeView1.Height=Height/2;

				listView1.Left=0;
				listView1.Top=Height/2;
				listView1.Width=Width;
				listView1.Height=Height/2;
			}
			listView1.Columns[0].Width=(listView1.Width/3)*2;
			listView1.Columns[1].Width=(listView1.Width/3)-1;			

			m_rectTree=new Rectangle(treeView1.Left,treeView1.Top,treeView1.Width,treeView1.Height);
			m_rectFiles=new Rectangle(listView1.Left,listView1.Top,listView1.Width,listView1.Height);

			FillTree();

			if (m_bBrowseForDirectory)
			{
				tbBtnTreeView.Enabled=false;
				tbBtnFileView.Enabled=false;
				tbBtnSplitView.Enabled=false;

				ToolBarButtonClickEventArgs e=new ToolBarButtonClickEventArgs(tbBtnTreeView);
				toolBar1_ButtonClick(null, e);
			}
			tbBtnOk.Enabled=false;
		}

		private Icon GetIcon(Assembly execAssembly, string name) 
		{			
			string ResName="PPCHelpReader." + name + ".ico";
			Stream stream = execAssembly.GetManifestResourceStream(ResName);
			return new Icon(stream);
		}

		private void ExpandNode(TreeNodeCollection ParentNode, string RootDir)
		{
			if (this.m_bExcludeWindowDir)
			{
				if (RootDir.ToLower().StartsWith(@"\windows"))
					return;
			}

			DirectoryInfo DI=new DirectoryInfo(RootDir);
			DirectoryInfo []Dirs=DI.GetDirectories();			

			// Sort Dirs
			ArrayList DirSorted=new ArrayList(Dirs.Length);			
			foreach(DirectoryInfo DI1 in Dirs)
			{
				DirSorted.Add(DI1);
			}
			DirSorted.Sort(new myDirSort());

			//
			// Thanks to BruceN (beelzeboris@hotmail.com) for this fix in the code
			// see http://www.codeproject.com/netcf/CHMReaderNet.asp?select=950326&df=100&forumid=51476&noise=5&msg=950326#xx948823xx
			//
			foreach(DirectoryInfo DI2 in DirSorted)
			{				
				if (this.m_bExcludeWindowDir)
				{
					if (DI2.FullName.ToLower().StartsWith(@"\windows"))
						continue;
				}

				TreeNode tn=new TreeNode(DI2.Name);
				tn.Tag=DI2.FullName;				
				//Console.WriteLine (tn.Tag.ToString ());
				tn.ImageIndex=6;
				tn.SelectedImageIndex=5;

				ParentNode.Add(tn);

				string Path = DI2.FullName;									//Crashed on @"\Network\NetworkPath on ServerName" share, so check for ' on '
				string NetworkShare = " on ";								//Should move this above the foreach loop
				char[] loc = NetworkShare.ToCharArray();					//Check for bad/disconnected network share
				int result = Path.IndexOf (NetworkShare, 0, Path.Length);	//If not found, will be -1
				if (result < 1)
				{
					ExpandNode(tn.Nodes,DI2.FullName);
				}
			}
			//
			//	End of fix.
			//
		}

		private void FillTree()
		{
			treeView1.Nodes.Clear();
			Cursor.Current=Cursors.WaitCursor;
			ExpandNode(treeView1.Nodes,@"\");
			Cursor.Current=Cursors.Default;
			treeView1.SelectedNode=treeView1.Nodes[0];
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.listView1 = new System.Windows.Forms.ListView();
			this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
			this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
			this.treeView1 = new System.Windows.Forms.TreeView();
			this.toolBar1 = new System.Windows.Forms.ToolBar();
			this.tbBtnOk = new System.Windows.Forms.ToolBarButton();
			this.tbBtnCancel = new System.Windows.Forms.ToolBarButton();
			this.tbBtnTreeView = new System.Windows.Forms.ToolBarButton();
			this.tbBtnFileView = new System.Windows.Forms.ToolBarButton();
			this.tbBtnSplitView = new System.Windows.Forms.ToolBarButton();
			this.mainMenu1 = new System.Windows.Forms.MainMenu();
			// 
			// listView1
			// 
			this.listView1.Columns.Add(this.columnHeader1);
			this.listView1.Columns.Add(this.columnHeader2);
			this.listView1.FullRowSelect = true;
			this.listView1.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
			this.listView1.Location = new System.Drawing.Point(0, 136);
			this.listView1.Size = new System.Drawing.Size(240, 136);
			this.listView1.View = System.Windows.Forms.View.Details;
			this.listView1.ItemActivate += new System.EventHandler(this.listView1_ItemActivate);
			this.listView1.SelectedIndexChanged += new System.EventHandler(this.listView1_SelectedIndexChanged);
			// 
			// columnHeader1
			// 
			this.columnHeader1.Text = "Name";
			this.columnHeader1.Width = 180;
			// 
			// columnHeader2
			// 
			this.columnHeader2.Text = "Size";
			this.columnHeader2.Width = 60;
			// 
			// treeView1
			// 
			this.treeView1.ImageIndex = -1;
			this.treeView1.SelectedImageIndex = -1;
			this.treeView1.Size = new System.Drawing.Size(240, 136);
			this.treeView1.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterSelect);
			// 
			// toolBar1
			// 
			this.toolBar1.Buttons.Add(this.tbBtnOk);
			this.toolBar1.Buttons.Add(this.tbBtnCancel);
			this.toolBar1.Buttons.Add(this.tbBtnTreeView);
			this.toolBar1.Buttons.Add(this.tbBtnFileView);
			this.toolBar1.Buttons.Add(this.tbBtnSplitView);
			this.toolBar1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick);
			// 
			// tbBtnOk
			// 
			this.tbBtnOk.ImageIndex = 0;
			// 
			// tbBtnCancel
			// 
			this.tbBtnCancel.ImageIndex = 1;
			// 
			// tbBtnTreeView
			// 
			this.tbBtnTreeView.ImageIndex = 2;
			// 
			// tbBtnFileView
			// 
			this.tbBtnFileView.ImageIndex = 3;
			// 
			// tbBtnSplitView
			// 
			this.tbBtnSplitView.ImageIndex = 4;
			// 
			// FileSelectDlg
			// 
			this.ControlBox = false;
			this.Controls.Add(this.treeView1);
			this.Controls.Add(this.listView1);
			this.Controls.Add(this.toolBar1);
			this.MaximizeBox = false;
			this.Menu = this.mainMenu1;
			this.MinimizeBox = false;
			this.Text = "Select CHM File";

		}
		#endregion

		private void treeView1_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
		{
			if (this.m_bBrowseForDirectory)
			{
				tbBtnOk.Enabled=true;
			}
			else
			{
				listView1.Items.Clear();
				DirectoryInfo DI=new DirectoryInfo((string)e.Node.Tag);

				ArrayList SortedFileList=new ArrayList();
				string []masks=m_Mask.Split(';');
				foreach(string mask in masks)
				{
					FileInfo []Files=DI.GetFiles(mask);
					foreach(FileInfo FI1 in Files)
						SortedFileList.Add(FI1);
				}				
				SortedFileList.Sort(new myFileSort());

				foreach(FileInfo FI2 in SortedFileList)
				{
					ListViewItem Item=new ListViewItem(FI2.Name);
					double Len=(double)FI2.Length;
					string Suffix="b";
					if (Len>(double)1024.0)
					{
						Len/=(double)1024.0;
						Suffix="Kb";
					}
					if (Len>(double)1024.0)
					{
						Len/=(double)1024.0;
						Suffix="Mb";
					}				
					Item.SubItems.Add(Len.ToString("0.##")+Suffix);
					Item.SubItems.Add(FI2.CreationTime.ToString());
					listView1.Items.Add(Item);
				}
			}
		}

		private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
		{
			if (e.Button==tbBtnOk)
			{
				if (this.m_bBrowseForDirectory)
				{
					if (treeView1.SelectedNode==null)
						return;

					FileName=treeView1.SelectedNode.Tag.ToString();
					DialogResult=DialogResult.OK;
					Close();
					return;
				}
				else
				{
					if (listView1.SelectedIndices.Count!=1)
						return;
				}
			
				FileName=treeView1.SelectedNode.Tag+@"\"+listView1.Items[listView1.SelectedIndices[0]].Text;
				DialogResult=DialogResult.OK;
				Close();
			}
			if (e.Button==tbBtnCancel)
			{
				DialogResult=DialogResult.Cancel;
				Close();
			}
			if (e.Button==tbBtnTreeView)
			{
				treeView1.Height=this.Height;
				listView1.Hide();
				treeView1.Show();
				this.Refresh();
			}			
			if (e.Button==tbBtnFileView)
			{
				listView1.Top=m_rectTree.Top;
				listView1.Height=this.Height;
				treeView1.Hide();
				listView1.Show();
				this.Refresh();
			}
			if (e.Button==tbBtnSplitView)
			{
				treeView1.Top=m_rectTree.Top;
				treeView1.Left=m_rectTree.Left;
				treeView1.Height=m_rectTree.Height;
				listView1.Top=m_rectFiles.Top;
				listView1.Left=m_rectFiles.Left;
				listView1.Height=m_rectFiles.Height;								
				treeView1.Show();
				listView1.Show();
				this.Refresh();
			}
		}

		private void listView1_ItemActivate(object sender, System.EventArgs e)
		{
			tbBtnOk.Enabled=true;
		}

		private void listView1_SelectedIndexChanged(object sender, System.EventArgs e)
		{			
			if (listView1.SelectedIndices.Count==1)
				tbBtnOk.Enabled=true;
			else
				tbBtnOk.Enabled=false;
		}
	}

    /// <summary>
    /// 
    /// </summary>
	public class myDirSort : IComparer  
	{
		// Calls CaseInsensitiveComparer.Compare with the parameters reversed.
		int IComparer.Compare(Object ax, Object ay )  
		{
			DirectoryInfo x=(DirectoryInfo)ax;
			DirectoryInfo y=(DirectoryInfo)ay;
			return x.Name.CompareTo(y.Name);
		}
	}
    /// <summary>
    /// 
    /// </summary>
	public class myFileSort : IComparer  
	{
		// Calls CaseInsensitiveComparer.Compare with the parameters reversed.
		int IComparer.Compare(Object ax, Object ay )  
		{
			FileInfo x=(FileInfo)ax;
			FileInfo y=(FileInfo)ay;
			return x.Name.CompareTo(y.Name);
		}
	}

}
